package com.xy.zookeeper.watch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZKConnectionWatcher implements Watcher {
    //计数器对象
    static CountDownLatch countDownLatch = new CountDownLatch(1);
    //连接对象
    static ZooKeeper zooKeeper;

    public static void main(String[] args) {
        try {
            zooKeeper = new ZooKeeper("192.168.247.128:2181",5000, new ZKConnectionWatcher());
            countDownLatch.await();
            System.out.println(zooKeeper.getSessionId());
            zooKeeper.addAuthInfo("digest", "itcast2:123456".getBytes());
            byte[] bs = zooKeeper.getData("/nodei", false, null);
            System.out.println(new java.lang.String(bs));
            Thread.sleep(50000);
            zooKeeper.close();
            System.out.println("结束");
        } catch (IOException | InterruptedException | KeeperException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getType() == Event.EventType.None) {
            switch (watchedEvent.getState()) {
                case SyncConnected:
                    System.out.println("连接成功");
                    countDownLatch.countDown();
                    break;
                case Disconnected:
                    System.out.println("断开连接");
                    break;
                case Expired:
                    System.out.println("会话过期");
                    break;
                case AuthFailed:
                    System.out.println("授权失败");
                    break;
            }
        }
    }
}
